package top.roadvast.aop.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

@Component  //把对象交给spring管理 存放到ioc容器中
@Aspect     //把当前对象定义为切面类 待会的切入点表达式 增强 也都需要在这个类中完成
public class TxManager {

    //切入点表达式
    //方法名就是切入点的id
    @Pointcut("execution(* top.roadvast.aop.service.impl.UserServiceImpl.*(..))")
    public void pointcut() {

    }
    
    @Around(value = "pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws SQLException {
        Object proceed = null;
        try {
            System.out.println("环绕增强");
            beginTransaction();
            proceed = joinPoint.proceed();
            commit();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            rollback();
        } finally {
            close();
        }
        return proceed;
    }

    //@Before(value = "pointcut()")
    //给pointcut 切入点表达式拦截到的方法做前置增强
    public  void beginTransaction() throws SQLException {
        System.out.println("开启");
    }

    //@AfterReturning(value = "pointcut()")
    //给pointcut 切入点表达式拦截到的方法做后置增强
    public  void commit() throws SQLException {
        System.out.println("提交");
    }

    //@AfterThrowing(value = "pointcut()")
    //给pointcut 切入点表达式拦截到的方法做异常增强
    public  void rollback() throws SQLException {
        System.out.println("回滚");
    }

    //@After(value = "pointcut()")
    //给pointcut 切入点表达式拦截到的方法做最终增强
    public  void close() throws SQLException {
        System.out.println("释放");
    }

}